package com.liuche.wiki.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuche.wiki.common.ErrorCode;
import com.liuche.wiki.constant.CommonConstant;
import com.liuche.wiki.exception.ThrowUtils;
import com.liuche.wiki.mapper.WikiMapper;
import com.liuche.wiki.model.dto.wiki.WikiQueryRequest;
import com.liuche.wiki.model.entity.Wiki;
import com.liuche.wiki.model.entity.User;
import com.liuche.wiki.model.vo.WikiVO;
import com.liuche.wiki.model.vo.UserVO;
import com.liuche.wiki.service.WikiService;
import com.liuche.wiki.service.UserService;
import com.liuche.wiki.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 知识库服务实现
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@Service
@Slf4j
public class WikiServiceImpl extends ServiceImpl<WikiMapper, Wiki> implements WikiService {

    @Resource
    private UserService userService;

    /**
     * 校验数据
     *
     * @param wiki
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validWiki(Wiki wiki, boolean add) {
        ThrowUtils.throwIf(wiki == null, ErrorCode.PARAMS_ERROR);
        // todo 从对象中取值
        String title = wiki.getTitle();
        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(title), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        // todo 补充校验规则
        if (StringUtils.isNotBlank(title)) {
            ThrowUtils.throwIf(title.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
        }
    }

    /**
     * 获取查询条件
     *
     * @param wikiQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Wiki> getQueryWrapper(WikiQueryRequest wikiQueryRequest) {
        QueryWrapper<Wiki> queryWrapper = new QueryWrapper<>();
        if (wikiQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = wikiQueryRequest.getId();
        Long notId = wikiQueryRequest.getNotId();
        String title = wikiQueryRequest.getTitle();
        String content = wikiQueryRequest.getContent();
        String searchText = wikiQueryRequest.getSearchText();
        String sortField = wikiQueryRequest.getSortField();
        String sortOrder = wikiQueryRequest.getSortOrder();
        List<String> tagList = wikiQueryRequest.getTags();
        Long userId = wikiQueryRequest.getUserId();
        // todo 补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tagList)) {
            for (String tag : tagList) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取知识库封装
     *
     * @param wiki
     * @param request
     * @return
     */
    @Override
    public WikiVO getWikiVO(Wiki wiki, HttpServletRequest request) {
        // 对象转封装类
        WikiVO wikiVO = WikiVO.objToVo(wiki);

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = wiki.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        wikiVO.setUser(userVO);
        // 2. 已登录，获取用户点赞、收藏状态
        long wikiId = wiki.getId();
        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {
        }
        // endregion

        return wikiVO;
    }

    /**
     * 分页获取知识库封装
     *
     * @param wikiPage
     * @param request
     * @return
     */
    @Override
    public Page<WikiVO> getWikiVOPage(Page<Wiki> wikiPage, HttpServletRequest request) {
        List<Wiki> wikiList = wikiPage.getRecords();
        Page<WikiVO> wikiVOPage = new Page<>(wikiPage.getCurrent(), wikiPage.getSize(), wikiPage.getTotal());
        if (CollUtil.isEmpty(wikiList)) {
            return wikiVOPage;
        }
        // 对象列表 => 封装对象列表
        List<WikiVO> wikiVOList = wikiList.stream().map(wiki -> {
            return WikiVO.objToVo(wiki);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = wikiList.stream().map(Wiki::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 已登录，获取用户点赞、收藏状态
        Map<Long, Boolean> wikiIdHasThumbMap = new HashMap<>();
        Map<Long, Boolean> wikiIdHasFavourMap = new HashMap<>();
        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {
        }
        // 填充信息
        wikiVOList.forEach(wikiVO -> {
            Long userId = wikiVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            wikiVO.setUser(userService.getUserVO(user));
        });
        // endregion

        wikiVOPage.setRecords(wikiVOList);
        return wikiVOPage;
    }

}
